package com.threeonemeeting.activity;

import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.MiscHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.list.DepartmentInfoList;
import com.threeonemeeting.list.EnrollFieldInfoList;
import com.threeonemeeting.list.PosInfoList;
import com.threeonemeeting.list.TradesInfoList;
import com.threeonemeeting.model.DepartmentInfo;
import com.threeonemeeting.model.EnrollFieldInfo;
import com.threeonemeeting.model.MeetingTradesInfo;
import com.threeonemeeting.model.PosInfo;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.tab.MultiActivityTab;
import com.threeonemeeting.task.EnrollMeetingTask;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.util.MiscUtil;

public class EnrollMeetingActivity extends BaseTabActivity implements ICallBack {

	private LinearLayout posLayout = null;
	private LinearLayout deptLayout = null;
	private LinearLayout tradesLayout = null;
	private int nMeetingId = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_enroll_meeting);
		init("参会报名");

		Intent i = this.getIntent();
		if (i == null) {
			finish();
			return;
		}

		nMeetingId = (Integer) i.getExtras().get("eid");

		initCtrl();
		initEnrollBtn();
	}

	private boolean checkInput() {

		EnrollFieldInfoList listFields = DataCenter.getInstance().listEnrollField;
		for (int i = 0; i < listFields.size(); i++) {
			EnrollFieldInfo info = listFields.get(i);
			if (info == null)
				continue;

			// 隐藏和可选字段不进行提示
			if (info.eStatus == EnrollFieldInfo.EStatus.Hide
					|| info.eStatus == EnrollFieldInfo.EStatus.Optional)
				continue;

			// 普通编辑框
			if (info.eType == EnrollFieldInfo.EType.Text) {

				int nId = 0;
				if (info.nFieldId == 0) {
					nId = Math.abs(info.strName.hashCode());
				} else {
					// 自定义字段
					nId = info.nFieldId;
				}

				EditText edit = (EditText) findViewById(nId);
				if (edit != null) {
					String strEdit = edit.getText().toString();
					if (strEdit.trim().equalsIgnoreCase("") == true) {
						MessageBox.showToast(EnrollMeetingActivity.this,
								info.strDesc + "必须输入!");
						return false;
					}
				}

			} else if (info.eType == EnrollFieldInfo.EType.Radio) {
			} else if (info.eType == EnrollFieldInfo.EType.CheckBox) {
			}
		}

		return true;
	}

	private void initEnrollBtn() {

		// 搜索按钮
		Button btnEnroll = (Button) findViewById(R.id.btn_enroll);
		OnClickListener enrollBtnClickListener = new OnClickListener() {

			public void onClick(View v) {

				// 检查各个字段是否已经填写
				boolean bCanEnroll = checkInput();
				if (bCanEnroll == false)
					return;

				// 能够提交
				EnrollFieldInfoList listFields = DataCenter.getInstance().listEnrollField;

				Bundle b = new Bundle();
				if (bCanEnroll == true) {

					// 提交各个字段的值
					for (int i = 0; i < listFields.size(); i++) {
						EnrollFieldInfo info = listFields.get(i);
						if (info == null)
							continue;

						// 隐藏和可选字段不进行提示
						if (info.eStatus == EnrollFieldInfo.EStatus.Hide)
							continue;

						int nId = 0;
						if (info.nFieldId == 0) {
							nId = Math.abs(info.strName.hashCode());
						} else {
							// 自定义字段
							nId = info.nFieldId;
						}

						// 普通编辑框
						if (info.eType == EnrollFieldInfo.EType.Text) {

							EditText edit = (EditText) findViewById(nId);
							if (edit != null) {
								String strEdit = edit.getText().toString();
								if (info.nFieldId == 0) {
									b.putString(info.strName,
											strEdit.toString());
								} else {
									b.putString("Fileld_" + nId,
											strEdit.toString());
								}
							}
						} else if (info.eType == EnrollFieldInfo.EType.Radio) {

							TextView tx = (TextView) findViewById(nId);
							if (tx == null)
								continue;

							String strSelectValue = tx.getText().toString();

							// 系统指定的行业，只能部门和人数三个为下拉选择
							if (info.nFieldId == 0) {

								// 报名人数
								if (info.strName.trim().equalsIgnoreCase(
										Const.Enroll.BuyCount) == true) {
									b.putString(info.strName, strSelectValue);
								}
								// 行业
								else if (info.strName.trim().equalsIgnoreCase(
										Const.Enroll.Industries) == true) {
									int nCategoryId = DataCenter.getInstance().listTrades
											.getTradesId(strSelectValue);
									b.putString(info.strName,
											String.valueOf(nCategoryId));

								}
								// 职位
								else if (info.strName.trim().equalsIgnoreCase(
										Const.Enroll.PosStatus) == true) {
									int nPosId = DataCenter.getInstance().listPosInfo
											.getPosId(strSelectValue);
									b.putString(info.strName,
											String.valueOf(nPosId));
								}
								// 部门
								else if (info.strName.trim().equalsIgnoreCase(
										Const.Enroll.Department) == true) {
									int nDepartmentId = DataCenter
											.getInstance().listDeptInfo
											.getDepartmentId(strSelectValue);
									b.putString(info.strName,
											String.valueOf(nDepartmentId));
								}
							} else {

								b.putString("Field_" + info.nFieldId,
										tx.toString());
							}
						}
					}
				}
				//
				EnrollMeetingTask task = new EnrollMeetingTask(
						EnrollMeetingActivity.this, EnrollMeetingActivity.this);
				b.putString("eid", String.valueOf(nMeetingId));
				b.putString(
						"uid",
						String.valueOf(DataCenter.getInstance().currentLoginUserInfo.nUserId));
				b.putString(
						"pass",
						String.valueOf(DataCenter.getInstance().currentLoginUserInfo.strPassword));
				TaskManager.addTask(task, b, false);
			}

		};
		if (btnEnroll != null) {
			btnEnroll.setOnClickListener(enrollBtnClickListener);
		}
	}

	private void initTradesCtrl(LinearLayout ctrlLayout) {
		tradesLayout = ctrlLayout;

		boolean bLocalSaved = MiscUtil.checkTradesInfo(getApplicationContext(),
				this);
		if (bLocalSaved == false)
			return;

		TradesInfoList list = DataCenter.getInstance().listTrades;
		final String datas[] = new String[list.size()];

		for (int j = 0; j < list.size(); j++) {
			MeetingTradesInfo info1 = list.get(j);
			if (info1 == null)
				continue;
			datas[j] = info1.strCategoryName;
		}

		layoutCombox(ctrlLayout, datas, Const.Enroll.Industries.hashCode());

		int nTradesId = DataCenter.getInstance().currentLoginUserInfo.nIndustry;
		String strTradesName = DataCenter.getInstance().listTrades
				.getTradesName(nTradesId);
		if (MiscHelper.isEmpty(strTradesName) != true) {
			TextView txSelectName = (TextView) findViewById(Math
					.abs(Const.Enroll.Industries.hashCode()));
			if (txSelectName != null)
				txSelectName.setText(strTradesName);
		}
	}

	private void initPosCtrl(LinearLayout ctrlLayout) {
		posLayout = ctrlLayout;

		boolean bLocalSaved = MiscUtil.checkPosStatus(getApplicationContext(),
				this);
		if (bLocalSaved == false)
			return;

		PosInfoList listPos = DataCenter.getInstance().listPosInfo;

		String datas[] = new String[listPos.size()];
		for (int j = 0; j < listPos.size(); j++) {
			PosInfo info1 = listPos.get(j);
			if (info1 == null)
				continue;
			datas[j] = info1.strPosName;
		}

		layoutCombox(ctrlLayout, datas, Const.Enroll.PosStatus.hashCode());

		int nPosStatusId = DataCenter.getInstance().currentLoginUserInfo.nPosStatus;
		String strPosStatusName = DataCenter.getInstance().listPosInfo
				.getPosInfoName(nPosStatusId);
		if (MiscHelper.isEmpty(strPosStatusName) != true) {
			TextView txSelectName = (TextView) findViewById(Math
					.abs(Const.Enroll.PosStatus.hashCode()));
			if (txSelectName != null)
				txSelectName.setText(strPosStatusName);
		}
	}

	private void initDepartmentCtrl(LinearLayout ctrlLayout) {
		deptLayout = ctrlLayout;

		boolean bLocalSaved = MiscUtil.checkDepartment(getApplicationContext(),
				this);
		if (bLocalSaved == false)
			return;

		DepartmentInfoList listDepts = DataCenter.getInstance().listDeptInfo;

		String datas[] = new String[listDepts.size()];
		for (int j = 0; j < listDepts.size(); j++) {
			DepartmentInfo info1 = listDepts.get(j);
			if (info1 == null)
				continue;
			datas[j] = info1.strDepartmentName;
		}

		layoutCombox(ctrlLayout, datas, Const.Enroll.Department.hashCode());

		int nDepartmentId = DataCenter.getInstance().currentLoginUserInfo.nDepartment;
		String strDepartmentName = DataCenter.getInstance().listDeptInfo
				.getDepartmentName(nDepartmentId);
		if (MiscHelper.isEmpty(strDepartmentName) != true) {
			TextView txSelectName = (TextView) findViewById(Math
					.abs(Const.Enroll.Department.hashCode()));
			if (txSelectName != null)
				txSelectName.setText(strDepartmentName);
		}
	}

	private void initCtrl() {
		LinearLayout fieldLayout = (LinearLayout) findViewById(R.id.field_layout);
		if (fieldLayout == null)
			return;

		EnrollFieldInfoList listFields = DataCenter.getInstance().listEnrollField;
		for (int i = 0; i < listFields.size(); i++) {
			final EnrollFieldInfo info = listFields.get(i);
			if (info == null)
				continue;

			// 如果当前字段隐藏，则不显示
			if (info.eStatus == EnrollFieldInfo.EStatus.Hide)
				continue;

			final LinearLayout fieldLineLayout = new LinearLayout(this);
			LinearLayout.LayoutParams fieldLineLayoutLp = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			fieldLineLayout.setPadding(0, MiscUtil.dp2px(5), 0,
					MiscUtil.dp2px(5));
			fieldLineLayout.setOrientation(LinearLayout.HORIZONTAL);
			fieldLayout.addView(fieldLineLayout, fieldLineLayoutLp);

			// 水平分割线
			final LinearLayout splitLineLayout = new LinearLayout(this);
			LinearLayout.LayoutParams splitLineLayoutLp = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, MiscUtil.dp2px(1));
			splitLineLayout.setBackgroundColor(0xFFCDCDCD);
			fieldLayout.addView(splitLineLayout, splitLineLayoutLp);

			// 添加名称的Layout
			final LinearLayout textLayout = new LinearLayout(this);
			LinearLayout.LayoutParams textLayoutLp = new LinearLayout.LayoutParams(
					MiscUtil.dp2px(86), LayoutParams.FILL_PARENT);
			textLayout.setOrientation(LinearLayout.HORIZONTAL);
			textLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			fieldLineLayout.addView(textLayout, textLayoutLp);

			// 文本
			LinearLayout.LayoutParams textviewLayoutLp = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			TextView textLabel = new TextView(this);
			textLabel.setTextColor(R.color.deepgray);
			textLabel.setTextSize(16);
			textLabel.setText(info.strDesc);
			TextPaint tp = textLabel.getPaint();
			tp.setFakeBoldText(true);
			textLayout.addView(textLabel, textviewLayoutLp);

			// 控件区域
			LinearLayout.LayoutParams fillparentLayoutLp = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

			LinearLayout ctrlLayout = new LinearLayout(this);
			fieldLineLayout.addView(ctrlLayout, fillparentLayoutLp);

			// 系统指定的行业，只能职位，行业、部门和人数四个个为下拉选择
			// 其余的默认是 text
			if (info.nFieldId == 0) {
				// 性别
				if (info.strName.trim().equalsIgnoreCase(Const.Enroll.Sex) == true) {
					final String datas[] = { "男", "女" };
					info.eType = EnrollFieldInfo.EType.Radio;
					layoutCombox(ctrlLayout, datas, Const.Enroll.Sex.hashCode());
					continue;
				}
				// 报名人数
				else if (info.strName.trim().equalsIgnoreCase(
						Const.Enroll.BuyCount) == true) {
					final String datas[] = { "1", "2", "3", "4", "5" };
					info.eType = EnrollFieldInfo.EType.Radio;
					layoutCombox(ctrlLayout, datas,
							Const.Enroll.BuyCount.hashCode());
					continue;
				}
				// 行业
				else if (info.strName.trim().equalsIgnoreCase(
						Const.Enroll.Industries) == true) {
					info.eType = EnrollFieldInfo.EType.Radio;
					initTradesCtrl(ctrlLayout);
					continue;
				}
				// 职位
				else if (info.strName.trim().equalsIgnoreCase(
						Const.Enroll.PosStatus) == true) {
					info.eType = EnrollFieldInfo.EType.Radio;
					initPosCtrl(ctrlLayout);
					continue;
				}
				// 部门
				else if (info.strName.trim().equalsIgnoreCase(
						Const.Enroll.Department) == true) {
					info.eType = EnrollFieldInfo.EType.Radio;
					initDepartmentCtrl(ctrlLayout);
					continue;
				}
			}

			if (info.eType == EnrollFieldInfo.EType.Text) {

				// editText
				final LinearLayout editLayout = new LinearLayout(this);
				LinearLayout.LayoutParams editLayoutLp = new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
				editLayoutLp.setMargins(MiscUtil.dp2px(5), 0,
						MiscUtil.dp2px(2), 0);
				editLayout.setOrientation(LinearLayout.HORIZONTAL);
				editLayout.setGravity(Gravity.CENTER_VERTICAL);
				editLayout.setPadding(MiscUtil.dp2px(15), MiscUtil.dp2px(2),
						MiscUtil.dp2px(15), MiscUtil.dp2px(2));
				editLayout
						.setBackgroundResource(R.drawable.round_corner_regtangle_10);
				ctrlLayout.addView(editLayout, editLayoutLp);

				// 编辑框
				EditText editText = (EditText) getLayoutInflater().inflate(
						R.layout.lib_edittext, null);

				if (info.nFieldId != 0) {
					editText.setId(info.nFieldId);
				} else {
					editText.setId(Math.abs(info.strName.hashCode()));

					// 如果是姓名
					if (DataCenter.getInstance().currentLoginUserInfo.nUserId != 0) {
						if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.RealName) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strRealName);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Email) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strEmail);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Mobile) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strMobile);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Company) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strCompany);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Address) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strAddress);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Zipcode) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strZipCode);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.City) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strCity);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Phone) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strPhone);
						} else if (info.strName.trim().equalsIgnoreCase(
								Const.Enroll.Fax) == true) {
							editText.setText(DataCenter.getInstance().currentLoginUserInfo.strFax);
						}
					}
				}

				editText.setHeight(45);
				editLayout.addView(editText, fillparentLayoutLp);

			}
			// 复选框
			else if (info.eType == EnrollFieldInfo.EType.Radio) {

				final String datas[] = info.strOptions.split("\\|");
				layoutCombox(ctrlLayout, datas, info.strOptions.hashCode());

			} else if (info.eType == EnrollFieldInfo.EType.CheckBox) {
				// String datas[] = info.strOptions.split("\\|");

			}

		}
	}

	private void layoutCombox(LinearLayout parentLayout,
			final String strDatas[], int nName) {

		final LinearLayout comboLayout = (LinearLayout) getLayoutInflater()
				.inflate(R.layout.lib_combox, null);
		final TextView txSelectName = (TextView) comboLayout
				.findViewById(R.id.select_name);
		txSelectName.setId(Math.abs(nName));

		if (strDatas.length >= 1) {
			txSelectName.setText(strDatas[0]);
		}

		LinearLayout.LayoutParams comboLayoutLp = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, MiscUtil.dp2px(35));
		comboLayoutLp.setMargins(MiscUtil.dp2px(5), 0, MiscUtil.dp2px(2), 0);
		comboLayout.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				new AlertDialog.Builder(
						((MultiActivityTab) EnrollMeetingActivity.this
								.getParent()))
						.setTitle("请选择")
						.setItems(strDatas,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {

										String strName = strDatas[which];
										txSelectName.setText(strName);

									}
								}).create().show();

			}

		});

		parentLayout.addView(comboLayout, comboLayoutLp);
	}

	public void doCallBack(Map<String, Object> map) {
		Integer msgType = (Integer) map.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			return;
		}

		Integer nError = (Integer) map.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			// 报名失败
			if (msgType == HttpConst.TASKTYPE_ENROLLMEETING) {

				if (nError != Const.AppError.ERROR_ENROLL)
					MessageBox.showToast(this, HttpUtil.getErrorDesc(nError));

				else {
					String strErrorMsg = (String) map.get("errmsg");
					if (strErrorMsg != null)
						MessageBox.showToast(this, strErrorMsg);
				}

				return;
			}
		}

		if (msgType == HttpConst.TASKTYPE_GETMEETINGTRADES) {

			initTradesCtrl(tradesLayout);

		} else if (msgType == HttpConst.TASKTYPE_GETPOSSTATUS) {

			initPosCtrl(posLayout);

		} else if (msgType == HttpConst.TASKTYPE_GETDEPARTMENTS) {

			initDepartmentCtrl(deptLayout);

		} else if (msgType == HttpConst.TASKTYPE_ENROLLMEETING) {
			MessageBox.showToast(this, "您已经报名成功");
			this.back();
		}

	}
}
